package com.ydzt.fanka.server.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.ydzt.fanka.server.domain.BufferRecord;
import com.ydzt.fanka.server.init.InitData;
import com.ydzt.fanka.server.persistence.BufferStore;

public class FileUtil {
	static Logger logger = Logger.getLogger(FileUtil.class.getName());
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	public static boolean deleteWaitTransmit(BufferRecord record){
		boolean flag = false;
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.wait_transmitPath);
		strBuilder.append("/");
		strBuilder.append(record.getBufferId());
		strBuilder.append(".hex");
		File file = new File(strBuilder.toString());
		strBuilder.delete(0, strBuilder.length());
		if(file.isFile() && file.exists()){
			boolean isDelete = file.delete();
			if(isDelete){
				flag = true;
			}
			else{
				flag = false;
			}
		}
		else{
			flag = false;
		}
		return flag;
	}
	
	public static boolean deleteOnlyReadFile(BufferRecord record){
		boolean flag = false;
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.onlyReadPath);
		strBuilder.append("/");
		strBuilder.append(record.getBufferId());
		strBuilder.append(".hex");
		File file = new File(strBuilder.toString());
		strBuilder.delete(0, strBuilder.length());
		
		if(file.isFile() && file.exists()){
			boolean isDelete = file.delete();
			if(isDelete){
				flag = true;
			}
			else{
				flag = false;
			}
		}
		else{
			flag = false;
		}
		return flag;
	}
	
	public static boolean deleteOnlyReadFile(BufferRecord record,String node){
		boolean flag = false;
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.onlyReadPath);
		strBuilder.append("/");
		strBuilder.append(node);
		strBuilder.append("/");
		strBuilder.append(record.getBufferId());
		strBuilder.append(".hex");
		File file = new File(strBuilder.toString());
		strBuilder.delete(0, strBuilder.length());
		if(file.isFile() && file.exists()){
			boolean isDelete = file.delete();
			if(isDelete){
				flag = true;
			}
			else{
				flag = false;
			}
		}
		else{
			flag = false;
		}
		return flag;
	}
	
	public long getFileSizes(File f) throws Exception{
        long s=0;
        if (f.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(f);
           s= fis.available();
           fis.close();
        } else {
            f.createNewFile();
        }
        return s;
    }
	
	public static long getlist(File f){
		long size = 0;
		try{
			File flist[] = f.listFiles();
			size=flist.length;
			for (int i = 0; i < flist.length; i++) {
				if (flist[i].isDirectory()) {
					size = size + getlist(flist[i]);
					size--;
				}
		    }
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		finally{
			
		}
	    return size;
	}
	
	public static boolean getErrorFile(){
		Date today = new Date();
		BufferRecord record = new BufferRecord();
		long size = 0;
		byte[] pkg = null;
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.errorPath);
		strBuilder.append("/");
		String todayFile = sdf.format(today);
		strBuilder.append(todayFile);
		strBuilder.append("/");
		strBuilder.append(InitData.jdbc_connect_error);
		String path = strBuilder.toString();
		strBuilder.delete(0, strBuilder.length());
		File f = new File(path);
		File flist[] = f.listFiles();
		size = flist.length;
		if(size != 0){
			File file = flist[0];
			try {
				pkg = IOUtil.toByteArrayTraditional(file.getAbsolutePath());
				if(pkg.length != 0){
					record.setBufferContent(pkg);
					record.setBufferId(file.getName().split("\\.")[0]);
					if(file.isFile() && file.exists()){
						boolean isDelete = file.delete();
						if(isDelete){
							BufferStore.writePackageIntoFile(record);
						}
						else{
							BufferStore.writePackageIntoErrorFile(record, InitData.write_into_buffer_error);
						}
					}
				}
				else{
					//logger.error("在buffer中取到长度为0的空文件");
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			finally{
				pkg = null;
				record = null;
				flist = null;
			}
			return true;
		}
		else{
			return false;
		}
	}
	

	public static BufferRecord getBufferFile(String node){
		BufferRecord record = new BufferRecord();
		long size = 0;
		byte[] pkg = null;
		File f = new File(InitData.bufferPath + node + "/");
		if (f.exists()) {
			File flist[] = f.listFiles();
			size = flist.length;
			if (size != 0) {
				File file = flist[0];
				try {
					pkg = IOUtil.toByteArrayTraditional(file.getAbsolutePath());
					if (pkg.length != 0) {
						// 20130828 如果是食堂的4001报文则改写结算日期
						// 解析参数类型
						byte[] paramTypeByteArray = new byte[2];
						System.arraycopy(pkg, 0, paramTypeByteArray, 0, 2);
						String paramType = ByteConvert
								.bcd2Str(paramTypeByteArray);
						if (paramType.equals("4001") && !InitData.nodeType.equals("00")) {
							// 改写结算日期
							byte[] tmpStmtDay = new byte[4];
							tmpStmtDay = ByteConvert.str2BcdNormal(DBHelper
									.getStmtDay());
							System.arraycopy(tmpStmtDay, 0, pkg, 23, 4);
						}

						record.setBufferContent(pkg);
						record.setBufferId(file.getName().split("\\.")[0]);
						if (file.isFile() && file.exists()) {
							boolean isDelete = file.delete();
							if (isDelete) {
								BufferStore.writePackageIntoOnlyRead(record,node);
								return record;
							} else {
							}
						}
					} else {
					}
				} catch (IOException e) {
					logger.error(e.getMessage());
				} finally {
					pkg = null;
					record = null;
					flist = null;
				}
			}

		} else {
			logger.info("路径" + InitData.bufferPath + "不正确");
		}
		return null;
	}
	
	public static BufferRecord getBufferFile(){
		BufferRecord record = new BufferRecord();
		long size = 0;
		byte[] pkg = null;
		File f = new File(InitData.bufferPath);
		if (f.exists()) {
			File flist[] = f.listFiles();
			size = flist.length;
			if (size != 0) {
				File file = flist[0];
				try {
					pkg = IOUtil.toByteArrayTraditional(file.getAbsolutePath());
					if (pkg.length != 0) {
						// 20130828 如果是食堂的4001报文则改写结算日期
						// 解析参数类型
						byte[] paramTypeByteArray = new byte[2];
						System.arraycopy(pkg, 0, paramTypeByteArray, 0, 2);
						String paramType = ByteConvert
								.bcd2Str(paramTypeByteArray);
						if (paramType.equals("4001") && !InitData.nodeType.equals("00")) {
							// 改写结算日期
							byte[] tmpStmtDay = new byte[4];
							tmpStmtDay = ByteConvert.str2BcdNormal(DBHelper
									.getStmtDay());
							System.arraycopy(tmpStmtDay, 0, pkg, 23, 4);
						}

						record.setBufferContent(pkg);
						record.setBufferId(file.getName().split("\\.")[0]);
						if (file.isFile() && file.exists()) {
							boolean isDelete = file.delete();
							if (isDelete) {
								BufferStore.writePackageIntoOnlyRead(record);
								return record;
							} else {
							}
						}
					} else {
					}
				} catch (IOException e) {
					logger.error(e.getMessage());
				} finally {
					pkg = null;
					record = null;
					flist = null;
				}
			}

		} else {
			logger.info("路径" + InitData.bufferPath + "不正确");
		}
		return null;
	}
	
	public static int isExistWithParamType(String paramType){
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.paramDefineFile);
		strBuilder.append("/");
		strBuilder.append(paramType);
		strBuilder.append(".xml");
		File f = new File(strBuilder.toString());
		String path = strBuilder.toString();
		strBuilder.delete(0, strBuilder.length());
		if(f.isFile()){
			return XmlUtil.GetRootNodeAttributeLength(path);
		}
		else{
			return 0;
		}
	}
	
	public static List<String> getFileList(String paramDefinePath){
		long size = 0;
		String filename;
		String parmPath = paramDefinePath;
		List<String> paramList = new ArrayList<String>();
		File f = new File(parmPath);
		File flist[] = f.listFiles();
		if(flist != null){
			size = flist.length;
			if(size != 0){
				for(int i = 0; i < size;i ++){
					File file = flist[i];
					filename = file.getName();
					paramList.add(filename);
				}
			}
			else{
				logger.info("参数_表映射 文件夹" + parmPath + "为空");
			}
		}
		else{
			logger.info("参数_表映射 文件夹" + parmPath + "不存在");
		}
		return paramList;
	}
}
